{% extends "base.html" %}

{% block title %}可用性监测{% endblock %}

{% block head %}
{{ super() }}
{% endblock %}

{% block content %}
<!-- 页面头 -->
<section class="content-header">
  <!--头部标题-->
  <h1>
    可用性监测
    <!--    <small>运维大盘</small>-->
  </h1>
  <!--面包屑-->
  <ol class="breadcrumb">
    <li><a href="/"><i class="fa fa-home"></i> 主页</a></li>
    <li class="active">可用性监测</li>
  </ol>
</section>

<!-- 页面内容 -->
<section class="content">

    <!--  prom balckbox 可用性检测  -->
  <div class="row">
    <div class="col-lg-12">
      <div class="box">
        <div class="box-header with-border">
          <h3 class="box-title">可用性监测（Prometheus）</h3>
          <div class="box-tools pull-right">
            <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
            </button>
            <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
          </div>
        </div>
        <div class="box-body" id="prom_aval_box">


        </div>
      </div>
    </div>
  </div>

  <!--  可用性检测box  -->
<!--  <div class="box">-->
<!--    <div class="box-header with-border">-->
<!--      <h3 class="box-title">可用性监测（1h）</h3>-->
<!--      <div class="box-tools pull-right">-->
<!--        <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>-->
<!--        </button>-->
<!--        <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>-->
<!--      </div>-->
<!--    </div>-->
<!--    &lt;!&ndash; /.box-header &ndash;&gt;-->
<!--    <div class="box-body">-->
<!--      &lt;!&ndash; 站点可用性（方块） &ndash;&gt;-->
<!--      <div class="row" id="aval_box" style="min-height: 170px">-->
<!--      </div>-->
<!--      &lt;!&ndash; /.row &ndash;&gt;-->
<!--    </div>-->
<!--    &lt;!&ndash; Loading (remove the following to stop the loading)&ndash;&gt;-->
<!--    <div id="loading" class="overlay" style="display: block">-->
<!--      <i class="fa fa-refresh fa-spin"></i>-->
<!--    </div>-->
<!--    &lt;!&ndash; end loading &ndash;&gt;-->
<!--  </div>-->




</section>
<!-- /.页面内容 -->
{% endblock %}

{% block script %}
<script src="/static/js/echarts.min.js"></script>

<script>
    function timestamp2time(timestamp) {
        //直接用 new Date(时间戳) 格式转化获得当前时间
        var timestamp1 = new Date(timestamp * 1000);
        //再利用拼接正则等手段转化为yyyy-MM-dd hh:mm:ss 格式
        dateString = timestamp1.toLocaleDateString().replace(/\//g, "-").substr(5) + "\n" + timestamp1.toTimeString().substr(0, 5)
        return dateString
    }

    function updateAvalNumber(prom_id, query_str, domId) {
        $.ajax({
            url: `/api/v1/prom/query?prom_id=${prom_id}&query=${query_str}`,
            success: function (data) {
                num = parseFloat(data.data.result[0].value[1]).toFixed(2)
                $(`#${domId}`).text(num)
                if (num < 95) {
                    $(`#${domId}`).css("color", "orange")
                }
                if (num < 80) {
                    $(`#${domId}`).css("color", "red")
                }
            }
        })
    }

    function drawAvalLines(prom_id, elemId, instance) {
        function draw(elemId, x, y1, y2) {
            // 基于准备好的dom，初始化echarts实例
            var myChart = echarts.init(document.getElementById(elemId));

            // 指定图表的配置项和数据
            var option = {
                title: {
                    text: instance,
                    left: "center"
                },
                tooltip: {
                    trigger: 'axis',
                },
                grid: {
                    top: '20%',
                    right: '2%',
                    left: '2%',
                    bottom: '10%',
                    containLabel: true
                },
                xAxis: {
                    data: x
                },
                yAxis: [
                    {
                        type: 'value',
                        name: '延迟',
                        position: 'left',
                        axisLine: {
                            lineStyle: {
                                color: '#5572C3'
                            }
                        },
                        axisLabel: {
                            formatter: '{value} s'
                        }
                    },
                    // {
                    //     type: 'value',
                    //     name: 'up',
                    //     min: 0,
                    //     // max: 1,
                    //     position: 'right',
                    //     axisLine: {
                    //         lineStyle: {
                    //             color: '#93CB79'
                    //         }
                    //     },
                    //     axisLabel: {
                    //         formatter: '{value}'
                    //     }
                    // },
                ],
                series: [
                    {
                        name: '延迟',
                        type: 'line',
                        data: y1,
                        symbol: 'none'
                    },
                    // {
                    //     name: 'up',
                    //     type: 'line',
                    //     data: y2,
                    //     symbol: 'none'
                    // }
                ]
            };

            // 使用刚指定的配置项和数据显示图表。
            myChart.setOption(option);

        }

        // 刷新数据2
        var u1 = $.ajax({
            url: `/api/v1/prom/query_range?prom_id=${prom_id}&time_range=hour&query=probe_duration_seconds{instance="${instance}"}`,
        })

        // 刷新数据
        var u2 = $.ajax({
            url: `/api/v1/prom/query_range?prom_id=${prom_id}&time_range=hour&query=probe_success{instance="${instance}"}`,
        })


        $.when(u1, u2).then(function (a1, a2) {
            // console.log("a1 ", a1)
            // console.log("a2", a2)
            let date = [], data1 = [], data2 = [];
            let a1_values = a1[0].data.result[0].values
            let a2_values = a2[0].data.result[0].values
            for (let i = 0, len = a1_values.length; i < len; i++) {
                // date.push(timestamp2time(a1_values[i][0]));
                data1.push(parseFloat(a1_values[i][1]).toFixed(2));
            }
            for (let i = 0, len = a2_values.length; i < len; i++) {
                date.push(timestamp2time(a2_values[i][0]));
                data2.push(parseFloat(a2_values[i][1]).toFixed(2));
            }
            // console.log(date)
            // console.log(data1)
            // console.log(data2)
            draw(elemId, date, data1, data2)
        })
    }


    function refreshAval() {
        $('#loading').show();
        $('#aval_box').empty();
        $.get('/api/v1/aval/list', function (data) {
            if (data.message === 'ok') {
                console.log(data)
                for (let i in data.data) {
                    let color = "bg-green"
                    if (data.data[i].aval_1h < 0.99) {
                        color = 'bg-yellow'
                    }
                    if (data.data[i].aval_1h < 0.9) {
                        color = 'bg-red'
                    }
                    if (data.data[i].acc_5m < 0.8) {
                        color = 'bg-yellow'
                    }
                    if (data.data[i].acc_5m < 0.5) {
                        color = 'bg-red'
                    }
                    let t = "    <div class=\"col-lg-2 col-xs-4\">\n" +
                        "      <div class=\"small-box " + color + "\">\n" +
                        "        <div class=\"inner\" style=\"text-align: center\">\n" +
                        "          <p>" + data.data[i].name + "</p>\n" +
                        "          <h3>" + data.data[i].aval_1h * 100 + "<sup style=\"font-size: 20px\">%</sup></h3>\n" +
                        "          <p style='color:rgba(255,255,255,0.8); font-size: 13px; margin-bottom: 0'>延迟:" + data.data[i].lat_1h + "s   采样率:" + data.data[i].acc_5m + "</p>\n" +
                        "        </div>\n" +
                        "        <a href=\"/aval/monitor/" + data.data[i].id + "\" class=\"small-box-footer\">更多信息 <i class=\"fa fa-arrow-circle-right\"></i></a>\n" +
                        "      </div>\n" +
                        "    </div>"
                    $('#aval_box').append(t)
                }
                ;
                $('#loading').hide()
            }
        });
    }

    $(function () {
        // refreshAval();

        // 设置自动刷新可用性
        // let a = 1;
        // let b = true;
        //
        // function do1() {
        //     if (!b) return;
        //     console.log("刷新次数：", a++)
        //     refreshAval();
        //     setTimeout(do1, 60000); // 每60秒刷新一次
        // }
        //
        // do1();

        // 调用接口，获取prom中的黑盒Endpoint
        let url_endpoints = '/api/prom/probe_endpoints_list'
        $.get(url_endpoints, function (data) {
            console.log(data)
            // 遍历
            for (let i in data.data) {
                // console.log(data.data[i].instance)
                let endpoint_grah_html = `          <div class="col-lg-2">
            <p><b>站点可用性：</b></p>
            <p>1H <span id="aval_1h_${i}"></span>%</p>
            <p>1D <span id="aval_1d_${i}"></span>%</p>
            <p>1W <span id="aval_1w_${i}"></span>%</p>
          </div>
          <div class="col-lg-10">
            <div id="chart_main_${i}" style="height:200px"></div>
          </div>`

                $('#prom_aval_box').append(endpoint_grah_html)

                // 测试，获取某一个Endpoint的黑盒监控数据，并画出图形
                let instance = data.data[i].instance
                let prom_id = data.data[i].prom_id
                let query_str_aval_1h = `avg_over_time(probe_success{instance="${instance}"}[1h])*100`
                let query_str_aval_1d = `avg_over_time(probe_success{instance="${instance}"}[1d])*100`
                let query_str_aval_1w = `avg_over_time(probe_success{instance="${instance}"}[1w])*100`
                // $(`#site_name_${i}`).text(instance)
                updateAvalNumber(prom_id, query_str_aval_1h, `aval_1h_${i}`)
                updateAvalNumber(prom_id, query_str_aval_1d, `aval_1d_${i}`)
                updateAvalNumber(prom_id, query_str_aval_1w, `aval_1w_${i}`)
                drawAvalLines(prom_id, `chart_main_${i}`, instance)
            }
        })


    });
</script>
{% endblock %}